package com.morn.fanfou.image;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import com.morn.fanfou.R;
import com.morn.fanfou.image.ImageDownload.DownloadImageListener;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Bitmap4View extends AsyncTask<Object, String, Bitmap> {
	private ImageDownload imageDownload;
	private ImageView imageView = null;
	private TextView textView = null;
	private ProgressBar progressBar = null;
	private boolean flag = false;
	private DownloadImageListener downloadImageListener = new DownloadImageListener() {

		@Override
		public void getStatus(int i, int size) {
			if (progressBar != null) {
				if (i % 1024 == 0) {

					Bitmap4View.this.publishProgress(i / 1024 + "/" + size / 1024 + " K");
					progressBar.setProgress(i * 100 / size);
				}
			}
		}

	};

	@Override
	protected void onCancelled() {
		imageDownload.stopDownLoad();
	};

	public Bitmap4View(Context context, HttpClient httpClient) {
		imageDownload = new ImageDownload(context, httpClient);
		imageDownload.setDownloadImageListener(downloadImageListener);
	}

	@Override
	protected Bitmap doInBackground(Object... params) {
		String urlStr = (String) params[0];
		imageView = (ImageView) params[1];
		textView = (TextView) params[2];
		progressBar = (ProgressBar) params[3];
		if (params.length > 4)
			flag = (Boolean) params[4];
		Bitmap bitmap = imageDownload.getImage(urlStr, flag);
		return bitmap;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		if (result != null) {
			imageView.setImageBitmap(result);
			imageView.setClickable(false);
			// TODO
			// Animation am = new ScaleAnimation(imageView.getWidth(),
			// result.getWidth(), imageView.getHeight(), result.getWidth());
			// am.setDuration(2000);
			// am.setRepeatCount(1);
			// imageView.setAnimation(am);
			// am.startNow();
			LayoutParams params = imageView.getLayoutParams();
			params.height = LayoutParams.WRAP_CONTENT;
			params.width = LayoutParams.WRAP_CONTENT;
			imageView.setLayoutParams(params);

			if (textView != null) {
				((ViewGroup) (textView.getParent())).removeView(textView);
			}
		} else {
			if (textView != null) {
				textView.setText(R.string.download_failed);
				imageView.setClickable(true);
			}
		}
		if (progressBar != null) {
			progressBar.setVisibility(View.INVISIBLE);
		}

	}

	@Override
	protected void onProgressUpdate(String... values) {
		if (textView != null) {
			textView.setText(values[0]);
		}
	}

}
